package com.neu.question.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neu.question.common.utils.CommonUtils;
import com.neu.question.common.utils.DateUtil;
import com.neu.question.common.utils.MailUtil;
import com.neu.question.common.utils.UUIDUtil;
import com.neu.question.domain.QuestionnaireInfo;
import com.neu.question.domain.Te;
import com.neu.question.mapper.ProjectInfoMapper;
import com.neu.question.mapper.QuestionInfoMapper;
import com.neu.question.mapper.QuestionnaireInfoMapper;
import com.neu.question.service.QuestionnaireInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author DELL
 * @description 针对表【questionnaire_info】的数据库操作Service实现
 * @createDate 2022-10-31 19:09:10
 */
@Service
public class QuestionnaireInfoServiceImpl extends ServiceImpl<QuestionnaireInfoMapper, QuestionnaireInfo>
        implements QuestionnaireInfoService {

    @Autowired
    private QuestionnaireInfoMapper questionnaireEntityMapper;

    @Autowired
    private ProjectInfoMapper projectEntityMapper;

    @Autowired
    private QuestionInfoMapper questionEntityMapper;

    @Override
    public PageInfo queryQuestionnaireInfo(Map<String, Object> map) {
        //分页查询
        PageHelper.startPage(Integer.parseInt(map.get("pageNum").toString()),
                Integer.parseInt(map.get("pageSize").toString()));
        List<Map<String, Object>> mapList = questionnaireEntityMapper.queryAllQuestionnaireList(map);
        PageInfo<Map<String, Object>> objectPageInfo = new PageInfo<>(mapList);
        return objectPageInfo;
    }

    @Override
    public Map<String, Object> queryQuestionnaireById(HashMap<String, Object> map) {
        Map<String, Object> result = questionnaireEntityMapper.queryQuestionnaireById(map);
        return result;
    }

    @Override
    public int modifyQuestionnaire(HashMap<String, Object> map) {
        //修改时间
        Date date = DateUtil.getCreateTime();
        map.put("lastUpdateDate", date);
        //修改人
        map.put("lastUpdatedBy", map.get("user"));
        int result = questionnaireEntityMapper.modifyQuestionnaire(map);
        return 1;
    }

    @Override
    public int modifyQuestionnaireAnswerTotal(HashMap<String, Object> map) {
        int result = questionnaireEntityMapper.modifyQuestionnaireAnswerTotal(map);
        return 1;
    }

    @Override
    public PageInfo queryQuestionnaireByNameAndProjectid(Map<String, Object> map) {
        //分页查询
        PageHelper.startPage(Integer.parseInt(map.get("pageNum").toString()),
                Integer.parseInt(map.get("pageSize").toString()));
        List<Map<String, Object>> mapList = questionnaireEntityMapper.queryQuestionnaireByNameAndProjectid(map);
        PageInfo<Map<String, Object>> objectPageInfo = new PageInfo<>(mapList);
        return objectPageInfo;
    }

    @Override
    public List<Map<String, Object>> queryQuestionnaireListById(Map<String, Object> map) {
        String projectid = projectEntityMapper.selectProjectIdByName(map.get("projectName").toString());
        map.put("projectId", projectid);
        List<Map<String, Object>> resultList = questionnaireEntityMapper.queryQuestionListByProjectId(map);
        return resultList;
    }

    @Override
    public String queryQuestionnaireIsStopStatus(String questionId) {
        String status = questionnaireEntityMapper.queryQuestionnaireIsStopStatus(questionId);
        return status;
    }

    @Override
    public int cancelQuestionnaireProject(String questionId) {
        int status = questionnaireEntityMapper.queryQuestionnaireStatusById(questionId);
        //问卷进行中
        if (status == 1) {
            return 0;
        }
        int result = questionnaireEntityMapper.cancelConnectionQuestionnaireProject(questionId);
        return 1;
    }

    @Override
    public int addQuestionnaireProject(Map<String, Object> map) {
        int result = questionnaireEntityMapper.addConnectionQuestionnaireProject(map);
        return 1;
    }

    @Override
    public int deleteQuestionnaireInfo(String questionId) {
        int status = questionnaireEntityMapper.queryQuestionnaireStatusById(questionId);
        //问卷进行中
        if (status == 3) {//关闭状态
            int result = questionnaireEntityMapper.deleteByPrimaryKey(questionId);
            return 1;
        }
        return 0;
    }

    @Override
    public int modifyQuestionnaireStatus(HashMap<String, Object> map) {
        int result = questionnaireEntityMapper.modifyQuestionnaireStatus(map);
        return 1;
    }

    //modifyQuestionnaireStatusToZero
    @Override
    public int modifyQuestionnaireStatusToZero(HashMap<String, Object> map) {
        int status = questionnaireEntityMapper.queryQuestionnaireStatusById(map.get("id").toString());
        if (status != 1) {
            int result = questionnaireEntityMapper.modifyQuestionnaireStatus(map);
            return 1;
        }
        return 0;
    }

    @Override
    public int addQuestionnaireInfo(Map<String, Object> map) {
        //判断问卷名称是否存在
        if (map.get("questionName") != null) {
            int userResult = questionnaireEntityMapper.queryExistQuestionnaire(map);
            if (userResult != 0) {
                //问卷名称已经存在
                return 0;
            }
        }
        //生成新的问卷id
        String id = UUIDUtil.getOneUUID();
        map.put("id", id);
        //添加问卷题目信息
        if (map.get("questionId") != null) {
            String preId = map.get("questionId").toString();
            Map<String, Object> preMap = questionnaireEntityMapper.queryQuestionnaireQuestionById(preId);
            if (preMap != null) {
                map.put("questionList", preMap.get("question"));
                map.put("questionTitle", preMap.get("questionTitle"));
            }
        }
        //创建时间
        Date date = DateUtil.getCreateTime();
        map.put("creationDate", date);
        map.put("lastUpdateDate", date);
        //创建人
        map.put("createdBy", map.get("user"));
        //修改人
        map.put("lastUpdatedBy", map.get("user"));
        //前台传入的时间戳转换
        String startTimeStr = map.get("startTime").toString();
        String endTimeStr = map.get("endTime").toString();
        Date startTime = DateUtil.getMyTime(startTimeStr);
        Date endTime = DateUtil.getMyTime(endTimeStr);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        //添加背景图片信息
        map.put("background", "0");
        //添加问卷信息
        int result = questionnaireEntityMapper.addQuestionnaire(map);
        return 1;
    }

    @Override
    public int modifyQuestionnaireInfo(HashMap<String, Object> map) {
        //判断问卷名称是否存在
        if (map.get("questionName") != null) {
            int userResult = questionnaireEntityMapper.queryExistQuestionnaire(map);
            if (userResult != 0) {
                //问卷名称已经存在
                return 0;
            }
        }
        //修改时间
        Date date = DateUtil.getCreateTime();
        map.put("lastUpdateDate", date);
        //修改人
        map.put("lastUpdatedBy", map.get("lastUpdatedBy"));
        //前台传入的时间戳转换
        String startTimeStr = map.get("startTime").toString();
        String endTimeStr = map.get("endTime").toString();
        Date startTime = DateUtil.getMyTime(startTimeStr);
        Date endTime = DateUtil.getMyTime(endTimeStr);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        int result = questionnaireEntityMapper.modifyQuestionnaireInfo(map);
        return 1;
    }

    @Override
    public int modifyQuestionnaireBackground(HashMap<String, Object> map) {
        //讲background字段转换为字符串
        String background = map.get("background").toString();
        map.put("background", background);
        int result = questionnaireEntityMapper.modifyQuestionnaireBackground(map);
        return 1;
    }

    //modifyQuestionnaireBackground

    @Override
    public Map<String, Object> queryQuestionnaireEndAndSmsContent(HashMap<String, Object> map) {
        Map<String, Object> resultMap = questionnaireEntityMapper.queryQuestContextEndById(map);
        return resultMap;
    }

    @Override
    public int addSendQuestionnaire(HashMap<String, Object> map) {
        //通过问卷id查询问卷开始结束时间
        //Map<String, Object> questionnaireMap = questionnaireEntityMapper.queryQuestionnaireStartEndTime(map.get
        // ("questionId").toString());
        //问卷开始时间
        //String startTime = questionnaireMap.get("startTime").toString();
        //问卷结束时间
        //String endTime = questionnaireMap.get("endTime").toString();
        //修改时间
        Date date = DateUtil.getCreateTime();
        map.put("lastUpdateDate", date);
        //修改人
        map.put("lastUpdatedBy", map.get("user"));
        //修改问卷状态为进行中、答卷数量0
        map.put("questionStop", "1");
        //短信发送方式
        if (map.get("sendType").equals("0")) {
            //前台传入的发布时间戳转换
            if (map.get("releaseTime").equals("")) {
                map.put("releaseTime", date);
            } else {
                String releaseTimeStr = map.get("releaseTime").toString();
                Date releaseTime = DateUtil.getMyTime(releaseTimeStr);
                map.put("releaseTime", releaseTime);
                //短信发送接口
       /* com.aliyun.dysmsapi20170525.Client client = null;
        try {
          client = ShortMessageConfig.createClient("ACCESS_KEY_ID", "ACCESS_KEY_SECRET");
          SendSmsRequest sendSmsRequest = new SendSmsRequest()
            .setSignName("问卷星链接")
            .setTemplateCode("SMS_154950909")
            .setPhoneNumbers("13775326232")
            .setTemplateParam("{\"code\":\"1234\"}");
          RuntimeOptions runtime = new RuntimeOptions();
          SendSmsResponse resp = client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
        */
            }
        }
        //邮箱发送方式
        if (map.get("sendType").equals("1")) {
            //创建学校统计表格
            questionnaireEntityMapper.createRecordCountSchool("record_count_school_" + map.get("questionId").toString());
            //创建答卷数据库表格
            questionnaireEntityMapper.createRecordCountAnswer("record_count_answer_" + map.get("questionId").toString());
            map.put("releaseTime", date);
            //163邮箱发送,个人电脑授权码：FGHJKFHDCPOJANNF
            // SMTP服务器: smtp.163.com
            try {
                //这里的邮箱是接受者的邮箱，和配置的邮箱不一样，配置的邮箱是发送者的邮箱
                List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("sendInfo");
                //循环发送邮件
                for (Map<String, Object> map1 : list) {
                    String emailAddress = map1.get("answerEmail").toString();
                    boolean result = emailAddress.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
                    //验证邮箱格式
                    if (!result) {
                        return 0;
                    }
                }
                for (Map<String, Object> map1 : list) {
                    String emailAddress = map1.get("answerEmail").toString();
                    //找到【联系人姓名】字段，替换为联系人姓名
                    String emailName = map1.get("answerName").toString();
                    String context = (String) map.get("context");
                    context = context.replace("联系人姓名", emailName);
                    //找到联系人所属学校
                    String schoolName = map1.get("answerBelong").toString();
                    //替换【填写问卷地址】字段，替换为填写问卷地址
                    String url = "http://127.0.0.1:8085/pages/previewQuestionnaire.html?id=" + map.get("questionId") + "&e0Rp=e&answerName=" + CommonUtils.enUnicode(emailName) + "&answerBelong=" + CommonUtils.enUnicode(schoolName);
                    context = context.replace("【填写问卷地址】", url);
                    //发送邮件
                    MailUtil.sendMail(emailAddress, (String) map.get("emailTitle"), context);
                    //判断学校是否存在
                    map1.put("name", schoolName);
                    map1.put("tableName", "record_count_school_" + map.get("questionId"));
                    //插入问卷总数
                    int count = questionnaireEntityMapper.querySchoolCount(map1);
                    if (count == 0) {
                        //将学校信息加入到学校统计表中
                        questionnaireEntityMapper.addRecordCountSchool(map1);
                    } else {
                        //将该学校的答卷发放数+1
                        questionnaireEntityMapper.modifyQuestionRecordSchoolAnswerTotal(map1);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        int result = questionnaireEntityMapper.addSendQuestionnaire(map);
        return 1;
    }

    @Override
    public int saveSendQuestionnaire(HashMap<String, Object> map) {
        //修改时间
        Date date = DateUtil.getCreateTime();
        map.put("lastUpdateDate", date);
        //修改人
        map.put("lastUpdatedBy", map.get("user"));
        //修改问卷状态为进行中、答卷数量0
        map.put("questionStop", "1");
        map.put("answerTotal", "0");
        //短信发送方式
        if (map.get("sendType").equals("0")) {
            //前台传入的发布时间戳转换
            if (map.get("releaseTime").equals("")) {
                map.put("releaseTime", date);
            } else {
                String releaseTimeStr = map.get("releaseTime").toString();
                Date releaseTime = DateUtil.getMyTime(releaseTimeStr);
                map.put("releaseTime", releaseTime);
            }
        }
        //邮箱发送方式
        if (map.get("sendType").equals("1")) {
            map.put("releaseTime", date);
        }
        if (map.get("sendType").equals("2")) {
            map.put("releaseTime", date);
        }
        int result = questionnaireEntityMapper.addSendQuestionnaire(map);
        return 1;
    }

    @Override
    public List<Map<String, Object>> queryHistoryQuestionnaire(HashMap<String, Object> map) {
        List<Map<String, Object>> mapList = questionnaireEntityMapper.queryHistoryQuestionnaire(map);
        return mapList;
    }

    @Override
    public String addAnswerQuestionnaire(List<Map<String, Object>> map) {
        String questionID = "";
        for (Map<String, Object> map1 : map) {
            questionID = map1.get("questionId").toString();
            //获取问卷信息
            HashMap<String, Object> questionIDmap = new HashMap<>();
            questionIDmap.put("questionId", map1.get("questionId"));
            Map<String, Object> questionnaire = questionnaireEntityMapper.queryQuestionnaireById(questionIDmap);
            //答卷题目数量
            Object answerList = map1.get("answerList");
            map1.put("questionNum", answerList.toString().split(",").length);
            //问卷中问题的所有标题
            map1.put("questionTitle", questionnaire.get("questionTitle"));
            map1.put("questionAnswer", map1.get("answerList").toString());//问卷中问题的所有答案编号
            map1.put("dataId", questionnaire.get("dataId"));//问卷类型
            //时间信息
            Date date = DateUtil.getCreateTime();
            map1.put("createDate", date);
            //计算答题时间
            long answerTimeLong = Long.parseLong(map1.get("answerTime").toString());
            long endTimeLong = Long.parseLong(map1.get("endTime").toString());
            long longTime = endTimeLong - answerTimeLong;
            String longTimeStr = String.valueOf(longTime);
            map1.put("longTime", longTimeStr);//答题时长
            map1.put("isValid", "1");//是否有效
            //自动生成答卷编号
            String answerId = UUIDUtil.getOneUUID();
            map1.put("answerId", answerId);//答卷编号
            //将url编码转换为中文
            String answerName = CommonUtils.deUnicode(map1.get("answerName").toString());
            map1.put("answerName", answerName);//答卷人姓名
            String answerBelong = CommonUtils.deUnicode(map1.get("answerBelong").toString());
            map1.put("answerBelong", answerBelong);//答卷人所属学校
            //学校统计表中的数据
            map1.put("effectiveAnswer", 1);
            map1.put("answerTotal", 0);
        }
        //添加答卷信息
        questionnaireEntityMapper.addQuestionRecordAnswerCount(map, "record_count_answer_" + questionID);
        //修改学校统计表，有效回收数+1
        questionnaireEntityMapper.modifyQuestionRecordAnswerSchool("record_count_school_" + questionID, map);
        return "提交成功，谢谢作答！";
    }

    @Override
    public List<Map<String, Object>> queryAllQuestionnaireByCreated(Map<String, Object> map) {
        List<Map<String, Object>> mapList = questionnaireEntityMapper.queryAllQuestionnaireByCreated(map);
        return mapList;
    }

    @Override
    public PageInfo queryQuestionnaireAboutSchool(HashMap<String, Object> map) {
        //查询是否存在学校统计表
        int tableExist = questionnaireEntityMapper.queryExistAnswerTable("record_count_school_" + map.get("questionId"));
        if (tableExist == 0) {
            return null;
        } else {
            PageHelper.startPage(Integer.parseInt(map.get("pageNum").toString()),
                    Integer.parseInt(map.get("pageSize").toString()));
            map.put("tableName", "record_count_school_" + map.get("questionId"));
            List<Map<String, Object>> mapList = questionnaireEntityMapper.queryRecordCountSchool(map);
            PageInfo<Map<String, Object>> objectPageInfo = new PageInfo<>(mapList);
            return objectPageInfo;
        }
    }

    @Override
    public Map<String, Object> queryQuestionnaireCount(HashMap<String, Object> map) {
        //查询是否存在答卷统计表
        String tableName = "record_count_school_" + map.get("questionId");
        int tableExist = questionnaireEntityMapper.queryExistAnswerTable(tableName);
        if (tableExist == 0) {
            return null;
        } else {
            map.put("tableName", "record_count_school_" + map.get("questionId"));
            Map<String, Object> map1 = questionnaireEntityMapper.queryQuestionRecordCountSchool(map);
            map.put("answerTotal", map1.get("answerTotal").toString());//总人数
            int questionCount = questionnaireEntityMapper.queryQuestionRecordCount("record_count_answer_" + map.get("questionId"));
            map.put("questionCount", questionCount);//总答卷数
            map.put("effectiveAnswer", map1.get("effectiveAnswer").toString());//有效答题人数
            //计算答题率
            double answerTotal = Double.parseDouble(map1.get("answerTotal").toString());
            double answerRateDouble = questionCount / answerTotal;
            String answerRate = CommonUtils.getPercent(answerRateDouble, 2);
            map.put("answerRate", answerRate);//答题率
            //获得问卷类型
            Map<String, Object> list = questionnaireEntityMapper.selectQuestionTitleById(map.get("questionId").toString());
            if (list == null) {
                return map;
            } else {
                map.put("dataId", list.get("dataId"));
                return map;
            }
        }
    }

    @Override
    public PageInfo queryRecordCountAnswer(HashMap<String, Object> map) {
        //查询是否存在答卷表
        int tableExist = questionnaireEntityMapper.queryExistAnswerTable("record_count_answer_" + map.get("questionId"));
        if (tableExist == 0) {
            return null;
        } else {
            PageHelper.startPage(Integer.parseInt(map.get("pageNum").toString()),
                    Integer.parseInt(map.get("pageSize").toString()));
            map.put("tableName", "record_count_answer_" + map.get("questionId"));
            List<Map<String, Object>> mapList = questionnaireEntityMapper.queryRecordCountAnswer(map);
            for (Map<String, Object> map1 : mapList) {
                map1.put("endTime", DateUtil.stampToDate(map1.get("endTime").toString()));
                map1.put("longTime", Long.parseLong(map1.get("longTime").toString()) / 1000);
            }

            PageInfo<Map<String, Object>> objectPageInfo = new PageInfo<>(mapList);
            return objectPageInfo;
        }
    }

    @Override
    public Map<String, Object> queryQuestionnaireQuestionTitle(HashMap<String, Object> map) {
        Map<String, Object> mapAns;
        if (map.get("questionId") == null) {
            return null;
        } else {
            String preId = map.get("questionId").toString();
            mapAns = questionnaireEntityMapper.queryQuestionnaireQuestionById(preId);
            if (mapAns == null) {
                return null;
            }
        }
        return mapAns;
    }

    @Override
    public List<Map<String, Object>> selectRecordAnswerDetail(HashMap<String, Object> map) {
        //查询是否存在答卷表
        int tableExist = questionnaireEntityMapper.queryExistAnswerTable("record_count_answer_" + map.get("questionId"));
        if (tableExist == 0) {
            return null;
        } else {
            Map<String, Object> tableMap = new HashMap<>();
            tableMap.put("tableName", "record_count_answer_" + map.get("questionId"));
            List<Map<String, Object>> result = questionnaireEntityMapper.selectRecordAnswerDetail(tableMap);
            for (Map<String, Object> map1 : result) {
                map1.put("endTime", DateUtil.stampToDate(map1.get("endTime").toString()));
            }
            return result;
        }
    }

    @Override
    public List<Te> queryEndtimeQues(String time, String sqid) {
        //从sqid 数据库查到  creatTime = time 的问卷数据
        String que = null;
        String ans = null;
        String pre = null;
        String time1 = null;
        String name = null;
        String school = null;

        Map<String, Object> tableMap = new HashMap<>();
        tableMap.put("tableName", "record_count_answer_" + sqid);
        //从数据库查询数据 并且存到maps中
        List<Map<String, Object>> maps = questionnaireEntityMapper.queryEndtime(tableMap);
        for (Map<String, Object> map1 : maps) {
            //调用DateUtil类  对时间进行转换并且比较
            String b = DateUtil.stampToDate(map1.get("endTime").toString());
            if (b.equals(time)) {
                //将对应的字段赋值
                que = (String) map1.get("questionTitle");
                ans = (String) map1.get("questionAnswer");
                time1 = b;
                name = (String) map1.get("answerName");
                school = (String) map1.get("answerBelong");
                break;
            }
        }

        // 将数据分解 分解成Te对象 并且存入集合
        String[] q = que.split("&");
        String[] a = ans.split(",");
        List<Te> t = new ArrayList<>();
        for (int i = 0; i < q.length; i++) {
            if (i == 0) {
                a[i] = a[i].replace("[", "");
            }
            if (i == q.length - 1) {
                a[i] = a[i].replace("]", "");
            }
            q[i] = "问题" + (i + 1) + ": " + q[i];
            t.add(new Te(q[i], a[i], name, time1, school));
        }
        return t;
    }

    @Override
    public int modifyQuestionnaireQuestion(HashMap<String, Object> map) {
        //创建一个list
        List<Map<String, Object>> mapList = new ArrayList<>();
        //获取id列表
        String idList = (String) map.get("idList");
        //将idList转换为list
        List<String> idList1 = JSON.parseObject(idList, new TypeReference<List<String>>() {
        });
        //遍历idList
        for (String id : idList1) {
            //根据id获取题目
            Map<String, Object> questionById = questionEntityMapper.getQuestionById(id);
            //处理questionOption
            String questionOption = (String) questionById.get("questionOption");
            List<Map<String, Object>> questionOptionList = JSON.parseObject(questionOption, new TypeReference<List<Map<String,
                    Object>>>() {
            });
            questionById.put("questionOption", questionOptionList);
            //将题目添加到list中
            mapList.add(questionById);
        }
        //获得questionnaireId
        String questionnaireId = (String) map.get("questionId");
        //构造map
        Map<String, Object> map1 = new HashMap<>();
        map1.put("id", questionnaireId);
        //将mapList转换为json
        String s = JSON.toJSONString(mapList);
        //去除开头结尾的[]
        s = s.substring(1, s.length() - 1);
        //获取questionnaireQuestion
        String questionnaireQuestion = questionnaireEntityMapper.queryQuestionnaireQuestionById(questionnaireId).get("question").toString();
        //去除结尾的]，加上,和s
        questionnaireQuestion = questionnaireQuestion.substring(0, questionnaireQuestion.length() - 1) + "," + s + "]";
        //将questionnaireQuestion放入map中
        map1.put("question", questionnaireQuestion);
        //构造questionTitle
        String questionTitle = "";
        for (Map<String, Object> map2 : mapList) {
            questionTitle += map2.get("questionTitle") + "&";
        }
        map1.put("questionTitle", questionTitle);
        //修改数据库
        int k = questionnaireEntityMapper.modifyQuestionOfQuestionnaire(map1);
        return 1;
    }

}




